﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityComponentSystem.Framework;
using EntityComponentSystem.Framework.Engine.Components;
using EntityComponentSystem.Framework.Engine.Entities;

namespace EntityComponentSystem.Demo.Aspects
{

    public interface IRicochetComponent : IComponent
    {
        IVector3d Position { get; }
        IVector3d Velocity { get; }

        void SetPosition(IVector3d pos);
        void SetVelocity(IVector3d vel);
    }

    public class RicochetComponent : EntityComponentSystem.Framework.Engine.Components.Component, IRicochetComponent
    {
        public IVector3d Position { get; private set; }
        public IVector3d Velocity { get; private set; }

        public void SetPosition(IVector3d pos)
        {
            Position = pos;
        }

        public void SetVelocity(IVector3d vel)
        {
            Velocity = vel;
        }

        public override void OnInit()
        {

        }

        public override void OnDispose()
        {

        }
    }

    public class RicochetSystem : EntityComponentSystem.Framework.Engine.Systems.System<RicochetComponent>
    {
        private Random r = new Random();

        public RicochetSystem(GameEngine ge)
            : base(ge)
        {


        }


        protected override void OnUpdate(long timeDelta, float timeDeltaF)
        {
            foreach (var c in this.AllComponents)
            {
                c.SetPosition(new Vector3d(c.Position.X + c.Velocity.X * timeDeltaF, c.Position.Y + c.Velocity.Y * timeDeltaF, 0));

                var vx = c.Velocity.X;
                var vy = c.Velocity.Y;
                if (c.Position.X >= 1000)
                    vx = -(float)(r.NextDouble() * 2.5f + 5);

                if (c.Position.X <= 0)
                    vx = (float)(r.NextDouble()  * 2.5f + 5);

                if (c.Position.Y >= 1000)
                    vy = -(float)(r.NextDouble()  * 2.5f + 5);

                if (c.Position.Y <= 0)
                    vy = (float)(r.NextDouble() * 2.5f + 5);


                c.SetVelocity(new Vector3d(vx, vy, 0));
            }
        }

        protected override void OnAddEntity(Entity e, RicochetComponent com)
        {
            var x = r.Next(0, 1000);
            var y = r.Next(0, 1000);

            com.SetPosition(new Vector3d(x, y, 0));
            com.SetVelocity(new Vector3d(x > 500 ? 5 : -5, y > 500 ? 5 : -5, 0));
        }

        protected override void OnRemoveEntity(Entity e, RicochetComponent com)
        {
        }

        protected override void OnDispose()
        {
        }
    }

}
